package cn.lzj.ymcc.service.impl;

import cn.lzj.ymcc.domain.*;
import cn.lzj.ymcc.dto.SmsCode2RedisDto;
import cn.lzj.ymcc.dto.SmsCodeDto;
import cn.lzj.ymcc.dto.UserRegisterDto;
import cn.lzj.ymcc.exception.GlobleException;
import cn.lzj.ymcc.feign.UaaLoginFeignClient;
import cn.lzj.ymcc.mapper.UserMapper;
import cn.lzj.ymcc.result.JSONResult;
import cn.lzj.ymcc.service.IMessageInvitecodeService;
import cn.lzj.ymcc.service.IUserAccountService;
import cn.lzj.ymcc.service.IUserBaseInfoService;
import cn.lzj.ymcc.service.IUserService;
import cn.lzj.ymcc.util.AssertUtil;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * <p>
 * 会员登录账号 服务实现类
 * </p>
 *
 * @author json.liao
 * @since 2022-07-07
 */
@Service

public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private SmsCodeDto smsCodeDto;
    @Autowired
    private IUserAccountService userAccountService;
    @Autowired
    private IUserBaseInfoService userBaseInfoService;
    @Autowired
    private IMessageInvitecodeService messageInvitecodeService;
    @Autowired
    private IUserService userService;
    @Autowired
    private UaaLoginFeignClient uaaLoginFeignClient;
    @GlobalTransactional(rollbackFor = Exception.class)
    @Override
    public void register(UserRegisterDto userRegisterDto) {
        //smskey  前缀加上手机号码
        String smskey ="SendMessage:" + userRegisterDto.getMobile();
        //获取上次发送的验证码，和时间戳
        SmsCode2RedisDto lastSendCode  = (SmsCode2RedisDto)redisTemplate.opsForValue().get(smskey);
        AssertUtil.isNotNull(lastSendCode,"验证码错误！！" );
        //比较
        //有邀请码，添加邀请码的逻辑==========================
        String inViteCode = userRegisterDto.getUrlcode();
        if(inViteCode!=null){
            if (inViteCode.length()!=4){ throw new GlobleException("邀请码错误！！邀请码是四位数"); }
            List<MessageInvitecode> messageInvitecodeList = messageInvitecodeService.selectList(null);
            for (MessageInvitecode messageInvitecode : messageInvitecodeList) {
                if(inViteCode.equals(messageInvitecode.getCode())){ throw new GlobleException("邀请码重复！！请换一个邀请码哦！"); }
            }
            //把邀请码存储到数据库中======邀请者和注册者的关系要联系起来======
            MessageInvitecode messageInvitecode = new MessageInvitecode();
            messageInvitecode.setCode(inViteCode);
/*            String userphone = userRegisterDto.getMobile();
            List<User> userList = userService.selectList(null);
            for (User user : userList) {
                String userPhone = user.getPhone();
                if(userPhone==userphone){
                    Long userId = user.getId();
                }
            }*/
            messageInvitecode.setUserId(13);
            messageInvitecodeService.insert(messageInvitecode);
        }
        AssertUtil.isEquals(lastSendCode.getCode(), userRegisterDto.getSmsCode(), "验证码错误！！");
        User user = findByPhone(userRegisterDto.getMobile());
        AssertUtil.isNull(user, "手机号已被注册！！");
        //通过feign调用user==================================
        Login login = new Login();
        login.setUsername(userRegisterDto.getMobile());
        //TODO 加密 之后做
        login.setPassword(userRegisterDto.getPassword());
        login.setType(Login.TYPE_WEB);
        JSONResult jsonResult = uaaLoginFeignClient.savalogin(login);

        if(!jsonResult.isSuccess()){
            throw new GlobleException("注册失败，保存登录信息失败！！");
        }
        Long loginId = Long.valueOf(jsonResult.getData().toString());

        //用户保存数据=====================
        Date date = new Date();
        user = new User();
        user.setCreateTime(date.getTime());
        user.setPhone(userRegisterDto.getMobile());
        user.setNickName(userRegisterDto.getMobile());
        user.setSecLevel(0);
        user.setLoginId(loginId);
        insert(user);


        //把User的id   设置给account 账户，保存账户===================
        UserAccount userAccount = new UserAccount();
        userAccount.setId(user.getId());
        userAccount.setCreateTime(date.getTime());
        userAccountService.insert(userAccount);

        //把user的 id 设置给base_info ,保存baseinfo====================
        UserBaseInfo userBaseInfo = new UserBaseInfo();
        userBaseInfo.setId(user.getId());
        userBaseInfo.setCreateTime(date.getTime());
        userBaseInfo.setRegChannel(userRegisterDto.getRegChannel());
        userBaseInfoService.insert(userBaseInfo);
    }
    public User findByPhone(String phone){
        Wrapper<User> wrapper = new EntityWrapper<>();
        wrapper.eq("phone", phone);
        return selectOne(wrapper);
    }
}
